package com.znjc.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.znjc.device.domain.DeviceBoard;
import com.znjc.device.mapper.DeviceBoardMapper;
import com.znjc.device.service.IDeviceBoardRefService;
import com.znjc.device.service.IDeviceBoardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author zengpc
 * @date 2024-01-22
 */
@Service
public class DeviceBoardServiceImpl extends ServiceImpl<DeviceBoardMapper, DeviceBoard> implements IDeviceBoardService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private IDeviceBoardRefService deviceBoardRefService;

    @Override
    public void saveDeviceBoards(List<DeviceBoard> boards) {
        List<DeviceBoard> oldList = this.list();
        if(CollectionUtils.isNotEmpty(oldList)){
           //新增的
            List<DeviceBoard> addList = boards.stream()
                    .filter(item -> !oldList.stream().anyMatch(other -> other.getBoardCode().equals(item.getBoardCode())))
                    .collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(addList)){
                this.saveBatch(addList);
            }
            //需要删除的
            List<DeviceBoard> delList = oldList.stream()
                    .filter(item -> !boards.stream().anyMatch(other -> other.getBoardCode().equals(item.getBoardCode())))
                    .collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(delList)){
                List<Long> delIds = delList.stream().map(DeviceBoard::getId).collect(Collectors.toList());
                boolean flag = this.removeByIds(delIds);
                if(flag){
                    //删除配置了的板子信息
                    List<String> delCodes = delList.stream().map(DeviceBoard::getBoardCode).collect(Collectors.toList());
                    deviceBoardRefService.deleteRefByBoardCode(delCodes);
                }
            }
        }else{
            this.saveBatch(boards);
        }
    }

    /**
     * 判断板子是否存在
     * @param code
     * @return
     */
    private Boolean verify(String code,Long deptId){
        LambdaQueryWrapper<DeviceBoard> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DeviceBoard::getBoardCode,code);
        wrapper.eq(DeviceBoard::getDeptId,deptId);
        int count =this.count(wrapper);
        return count > 0 ? false : true;
    }
}
